package com.example.dangdangbackend.controller;

import com.example.dangdangbackend.DTO.AddOrderDTO;
import com.example.dangdangbackend.VO.OrderAndItemVO;
import com.example.dangdangbackend.VO.OrderDetailVO;
import com.example.dangdangbackend.common.CustomException;
import com.example.dangdangbackend.entity.Order;
import com.example.dangdangbackend.entity.Result;
import com.example.dangdangbackend.service.ItemService;
import com.example.dangdangbackend.service.OrderService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ItemService itemService;

    @PostMapping("/addOrder")
    public Result<Order> addOrder(AddOrderDTO addOrderDTO){
        log.info("信息为-----------{}",addOrderDTO.toString());
        if(addOrderDTO.getAddressId()==0){
            throw new CustomException("请选择地址");
        }
        //        先进行插入操作
        Order order = orderService.addOrder(addOrderDTO);
        //    再进行更新操作
       if(order!=null){
           int orderId = order.getOrderId();
           try{
               itemService.setItemOrder(orderId);
           }catch (Exception e){
               return Result.error("创建订单失败");
           }
       }else {
           return Result.error("创建订单失败");
       }

        return Result.success(order);
    }

    @PostMapping("/getOrderDetail")
    public Result<PageInfo<OrderDetailVO>> getOrderDetail(int pageSize, int pageNum){

        PageInfo<OrderDetailVO> pageInfo = orderService.getOrderDetail(pageSize, pageNum);
        return Result.success(pageInfo);
    }

    @PostMapping("/getOrderAndItemDetail")
    public Result<OrderAndItemVO> getOrderAndItemDetail(int orderId){
        log.info("具体为"+orderId);
        OrderAndItemVO byOrderId = orderService.findOrderAndItemsByOrderId(orderId);
        return Result.success(byOrderId);
    }

    @GetMapping("/getOrderById")
    public Result<Order> getOrderById(@Param("orderId") int orderId){

        return Result.success(orderService.getOrderByOrderId(orderId));
    }
}
